/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.st.service;

import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.st.config.Constant;
import com.jeesite.modules.st.dao.StInventoryBillDao;
import com.jeesite.modules.st.dao.StInventoryBillDetailDao;
import com.jeesite.modules.st.dao.StProductBillBatchDetailDao;
import com.jeesite.modules.st.entity.*;
import com.jeesite.modules.st.pojo.SourceMaterial;
import com.jeesite.modules.st.utils.BillJudge;
import com.jeesite.modules.st.utils.BillUtil;
import com.jeesite.modules.st.utils.PdfUtils;
import com.jeesite.modules.st.utils.qr.QRCodeUtil;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.utils.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 出入库单Service
 *
 * @author HOHD
 * @version 2020-12-16
 */
@Service
@Transactional(readOnly = true)
public class StInventoryBillService extends CrudService<StInventoryBillDao, StInventoryBill> {

    @Autowired
    private StInventoryBillDetailDao stInventoryBillDetailDao;

    /**
     * 获取单条数据
     *
     * @param stInventoryBill
     * @return
     */
    @Override
    public StInventoryBill get(StInventoryBill stInventoryBill) {
        StInventoryBill entity = super.get(stInventoryBill);
        if (entity != null) {
            StInventoryBillDetail stInventoryBillDetail = new StInventoryBillDetail(entity);
            stInventoryBillDetail.setStatus(StInventoryBillDetail.STATUS_NORMAL);
            entity.setStInventoryBillDetailList(stInventoryBillDetailDao.findList(stInventoryBillDetail));
        }
        return entity;
    }

    /**
     * 查询分页数据
     *
     * @param stInventoryBill 查询条件
     * @return
     */
    @Override
    public Page<StInventoryBill> findPage(StInventoryBill stInventoryBill) {
        return super.findPage(stInventoryBill);
    }

    @Autowired
    StWarehouseInventoryService stWarehouseInventoryService;
    @Autowired
    StCheckLogService stCheckLogService;

    @Autowired
    StProductBillBatchDetailDao stProductBillBatchDetailDao;

    @Autowired
    StStockCheckBillService stStockCheckBillService;
    @Autowired//优先级
    StProductRecordService stProductRecordService;

    @Resource
    BillUtil billUtil;

    @Transactional(readOnly = false)
    public void saveTakeStock(StInventoryBill stInventoryBill, Boolean less, Boolean more) {
        //保存
        stInventoryBill.setApproveState(Constant.st_approve_status.make);
        List<StInventoryBillDetail> listPrimary = stInventoryBill.getStInventoryBillDetailList();
        if (more) {
            stInventoryBill.setLoss(Constant.loss_or_profit.profit);
            List<StInventoryBillDetail> list = new ArrayList<>();
            List<StInventoryBill> queryList = findList(stInventoryBill);
            for (StInventoryBillDetail stInventoryBillDetail : listPrimary) {
                if (stInventoryBillDetail.getNumber() > 0) {
                    changeInfo(stInventoryBillDetail);
                    list.add(stInventoryBillDetail);
                }
            }
            stInventoryBill.setStInventoryBillDetailList(list);
            stInventoryBill.setInOrOut(BillUtil.BillType.inventoryProfitBill.getBillCode());
            if (queryList.isEmpty())
                save(stInventoryBill);
        }
        if (less) {
            stInventoryBill.setLoss(Constant.loss_or_profit.loss);
            stInventoryBill.setInOrOut(null);
            List<StInventoryBill> queryList = findList(stInventoryBill);
            List<StInventoryBillDetail> list = new ArrayList<>();
            for (StInventoryBillDetail stInventoryBillDetail : listPrimary) {
                if (stInventoryBillDetail.getNumber() < 0) {//亏的
                    stInventoryBillDetail.setNumber(-stInventoryBillDetail.getNumber());//这一步在前面会直接掉坑里面！！！！！
                    changeInfo(stInventoryBillDetail);
                    list.add(stInventoryBillDetail);
                }
            }
            stInventoryBill.setStInventoryBillDetailList(list);
            stInventoryBill.setInOrOut(BillUtil.BillType.inventoryLossBill.getBillCode());
            stInventoryBill.setId(null);
            if (queryList.isEmpty())
                save(stInventoryBill);
        }
// 把保存的捞出来 join
        String primaryId = stInventoryBill.getPrimaryId();
        StInventoryBill query = new StInventoryBill();
        query.setPrimaryId(primaryId);
        List<StInventoryBill> queryList = findList(query);
        String[] bill = new String[queryList.size()];
        for (int i = 0; i < queryList.size(); i++) {
            StInventoryBill stInventoryBill1 = queryList.get(i);
            String id = stInventoryBill1.getId();
            String billNo = stInventoryBill1.getBillNo();
            bill[i] = billNo + "_" + id;
        }
        StTakeStockBill stTakeStockBill = stTakeStockBillService.get(primaryId);
        stTakeStockBill.setInventoryBill(StringUtils.join(bill, ","));
        stTakeStockBillService.update(stTakeStockBill);
    }

    @Autowired
    StTakeStockBillService stTakeStockBillService;

    void changeInfo(StInventoryBillDetail stInventoryBillDetail) {
        String materialName = stInventoryBillDetail.getMaterialName();//是code
        StMaterialRecord stMaterialRecord = new StMaterialRecord();
        stMaterialRecord.setMaterialCode(materialName);
        StMaterialRecord queryRes = stMaterialRecordService.findMP(stMaterialRecord).get(0);//只会有一个
        String packType = queryRes.getPackType();
        String id = queryRes.getId();
        stInventoryBillDetail.setMaterialName(id);
        stInventoryBillDetail.setPackType(packType);
    }

    public static class CheckResult {
        // 一种情况是检验产品的情况
        //一种是检测订单是否可以回退
        public int checkStatus;
        public String message;
    }

    @Transactional(readOnly = false)
    public String approve(StInventoryBill stInventoryBillT, int approveStatusT) {
        StInventoryBill stInventoryBill = super.get(stInventoryBillT.getId(), false);
        Integer billType = stInventoryBill.getInOrOut();
        Integer approveState = stInventoryBill.getApproveState();
        List<StInventoryBillDetail> stInventoryBillDetailList = stInventoryBill.getStInventoryBillDetailList();
        if (4 == approveState && 2 == approveStatusT) {
            // 弃审
            //撤回的时候不能立马又检测
//            synchronized (Constant.st_product_bill_stock_in_status.checkLock) {
            if (billType == 31 || billType == 32) {//成品，半成品
                for (StInventoryBillDetail stInventoryBillDetail : stInventoryBillDetailList) {
                    String batchId = stInventoryBillDetail.getBatchId();
                    StProductBillBatchDetail stProductBillBatchDetailT = new StProductBillBatchDetail();
                    stProductBillBatchDetailT.setId(batchId);
                    stProductBillBatchDetailT = stProductBillBatchDetailDao.get(stProductBillBatchDetailT);

                    stProductBillBatchDetailT.setStockInStatus(Constant.st_product_bill_stock_in_status.not_in);//
                    stProductBillBatchDetailDao.update(stProductBillBatchDetailT);//动作1
                    removeWarehouseLog(stInventoryBillDetail.getId());//删除仓库操作日志
                    //todo 看一下有没有出库记录
                    String batchNumber = stInventoryBillDetail.getBatchNumber();
                    deleteCheckByBatchNumber(batchNumber);
                }
//                }
            }
            if (billType == BillUtil.BillType.saleOutBill.getBillCode() || billType == BillUtil.BillType.purchaseInBill.getBillCode()
                    ||
                    //盘盈，盘亏
                    billType == BillUtil.BillType.inventoryProfitBill.getBillCode() || billType == BillUtil.BillType.inventoryLossBill.getBillCode()
            ) {
                //销售出库，采购单
                for (StInventoryBillDetail stInventoryBillDetail : stInventoryBillDetailList) {
                    removeWarehouseLog(stInventoryBillDetail.getId());//删除仓库操作日志
                }
            }
        }
        if (2 == approveState && 4 == approveStatusT) {//制单到已审核
            if (BillUtil.BillType.purchaseInBill.getBillCode() == billType) {
                for (StInventoryBillDetail stInventoryBillDetail : stInventoryBillDetailList) {
                    Integer checkState = stInventoryBillDetail.getCheckState();
                    String id = stInventoryBillDetail.getId();

                    StCheckLog query = new StCheckLog();
                    query.setInventoryBillDetailId(id);
                    StCheckLog stCheckLog = stCheckLogService.findList(query).get(0);
                    Integer stockInNumber = stCheckLog.getStockInNumber();
                    Integer number = stInventoryBillDetail.getNumber();
                    if (number > stockInNumber) {
                        return stInventoryBillDetail.getMaterialRecord().getMaterialName() + "-允许入库数量超额";
                    }
                    if (Constant.st_material_check.ok != checkState) {
                        return stInventoryBillDetail.getMaterialRecord().getMaterialName() + "-未通过检验";
                    }
                }
                for (StInventoryBillDetail stInventoryBillDetail : stInventoryBillDetailList) {
                    Integer checkState = stInventoryBillDetail.getCheckState();
                    if (4 == checkState) {//通过状态进行插入
                        saveWarehouseInventory(billType, stInventoryBillDetail, stInventoryBillDetail.getBillNo());
                    }
                }
                //其他状态卡不卡不知道
            } else if (billType == BillUtil.BillType.productInBill.getBillCode() ||
                    billType == BillUtil.BillType.productHalfInBill.getBillCode()) {//成品，半成品入库
                for (StInventoryBillDetail stInventoryBillDetail : stInventoryBillDetailList) {
                    String batchId = stInventoryBillDetail.getBatchId();
                    StProductBillBatchDetail stProductBillBatchDetailT = new StProductBillBatchDetail();
                    stProductBillBatchDetailT.setId(batchId);
                    stProductBillBatchDetailT = stProductBillBatchDetailDao.get(stProductBillBatchDetailT);

                    stProductBillBatchDetailT.setStockInStatus(Constant.st_product_bill_stock_in_status.in);//
                    stProductBillBatchDetailDao.update(stProductBillBatchDetailT);//动作1

                    saveWarehouseInventory(billType, stInventoryBillDetail, stInventoryBillDetail.getBillNo());//动作3

                    if (billType == BillUtil.BillType.productInBill.getBillCode()) {//只有成品才需要检验
                        String productId = stInventoryBillDetail.getMaterialName();
                        // 只写了成品还有半成品呢
                        StProductRecord stProductRecord = stProductRecordService.get(productId);
                        StProductBillBatchDetail stProductBillBatchDetail = new StProductBillBatchDetail();
                        String[] ids = new String[]{batchId};
                        stProductBillBatchDetail.setCpIdArr(ids);
                        stProductBillBatchDetail = stProductBillBatchDetailDao.findDetail(stProductBillBatchDetail).get(0);

                        saveCheck(stProductRecord, stProductBillBatchDetail);
                    }
                }
            } else if (billType == BillUtil.BillType.saleOutBill.getBillCode()) {
                //盘点批次是否检验过
                for (StInventoryBillDetail stInventoryBillDetail : stInventoryBillDetailList) {
                    String batchNumber = stInventoryBillDetail.getBatchNumber();
                    String[] batchArr = batchNumber.split(",");
                    for (String batch : batchArr) {
                        String warehouse = batch.split("_")[0];
                        String bn = batch.split("_")[1];
                        String number = batch.split("_")[2];
                        stInventoryBillDetail.setBatchNumber(bn);
                        stInventoryBillDetail.setNumber(Integer.valueOf(number));
                        stInventoryBillDetail.setWarehousePosition(warehouse);
                        saveWarehouseInventory(billType, stInventoryBillDetail, stInventoryBillDetail.getBillNo());
                    }
                    stInventoryBillDetail.setWarehousePosition(null);//本来就应该没有，记录最后一次像什么样子
                }
            } else {//其他情况
                for (StInventoryBillDetail stInventoryBillDetail : stInventoryBillDetailList) {
                    saveWarehouseInventory(billType, stInventoryBillDetail, stInventoryBillDetail.getBillNo());
                }
            }
        }

        stInventoryBill.setApproveState(approveStatusT);
        User user = UserUtils.getUser();
        stInventoryBill.setApproveManCode(user.getUserCode());
        stInventoryBill.setApproveManName(user.getUserName());
        save(stInventoryBill);
        return "";
    }

    @Autowired
    StStockCheckHistoryService stStockCheckHistoryService;

    /**
     * 生成检验记录
     *
     * @param stProductRecord
     * @param stProductBillBatchDetail
     */
    private void saveCheck(StProductRecord stProductRecord, StProductBillBatchDetail stProductBillBatchDetail) {
        String productCode = stProductRecord.getProductCode();
        String productName = stProductRecord.getProductName();
        StStockCheckBill stStockCheckBill = new StStockCheckBill();
        String batchNumber = stProductBillBatchDetail.getBatchNumber();
        stStockCheckBill.setBatchNumber(batchNumber);
        List<StStockCheckBill> list = stStockCheckBillService.findList(stStockCheckBill);
        if (list.isEmpty()) {//第一次

        } else if (list.size() == 1) {
            stStockCheckBill = list.get(0);
            stStockCheckBill.setIsDel(Constant.is_del.not_del);//显示出来
            stStockCheckBill.setCheckType(Constant.st_stock_check_state.not_check);
        } else {
            throw new IllegalArgumentException("肯定有哪里是错了");
        }
        Integer perWeight //库存数量
                = stProductBillBatchDetail.getParentId().getPerWeight();
        Integer caseNumber = stProductBillBatchDetail.getCaseNumber();
        String specification//包装规格
                = stProductBillBatchDetail.getSpecification();
        stStockCheckBill.setCaseNumber(caseNumber);
        stStockCheckBill.setProductCode(productCode);
        stStockCheckBill.setProductName(productName);
        stStockCheckBill.setStockNumber(perWeight);
        stStockCheckBill.setPackType(specification);
        stStockCheckBillService.save(stStockCheckBill);//动作2
    }


    private void deleteCheckByBatchNumber(String batchNumber) {
        StStockCheckBill stStockCheckBill = new StStockCheckBill();
        stStockCheckBill.setBatchNumber(batchNumber);
        stStockCheckBill = stStockCheckBillService.findList(stStockCheckBill).get(0);
        stStockCheckBill.setIsDel(Constant.is_del.del);
        stStockCheckBillService.update(stStockCheckBill);
//        String id = stStockCheckBill.getId();
//        StStockCheckHistory stNull = new StStockCheckHistory();
//        stNull.setParentId(id);
//        List<StStockCheckHistory> list = stStockCheckHistoryService.findList(stNull);
//        for (StStockCheckHistory stStockCheckHistory : list) {
//            stStockCheckHistoryService.delete(stStockCheckHistory);
//        }
//        stStockCheckBillService.delete(stStockCheckBill);

    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    @Autowired
    StMaterialRecordService stMaterialRecordService;

    @Resource
    PdfUtils pdfUtils;
    @Value("${qr_path}")
    String qrPath;
    @Value("${url_prefix}")
    String pdfHost;

    public String print(String printId) {
        StInventoryBillDetail stInventoryBillDetail = new StInventoryBillDetail();
        stInventoryBillDetail.idIn(printId.split(","));
        List<StInventoryBillDetail> list = stInventoryBillDetailDao.findList(stInventoryBillDetail);
        List<SourceMaterial> printList = new ArrayList<>();
        for (StInventoryBillDetail inventoryBillDetail : list) {
            String materialId = inventoryBillDetail.getMaterialName();
            StMaterialRecord stMaterialRecord = stMaterialRecordService.get(materialId);
            String materialName = stMaterialRecord.getMaterialName();
            String batchNumber = inventoryBillDetail.getBatchNumber();
            String materialCode = stMaterialRecord.getMaterialCode();
            String packType = inventoryBillDetail.getPackType();//包装规格
            Date passDate = inventoryBillDetail.getPassDate();
            SourceMaterial sourceMaterial = new SourceMaterial();
            sourceMaterial.materialName = materialName;
            sourceMaterial.batchNumber = batchNumber;
            sourceMaterial.materialCode = materialCode;
            sourceMaterial.packType = packType;
            String passDateStr = sdf.format(passDate);
            sourceMaterial.passDate = passDateStr;

            String barCode = materialCode + "_" + batchNumber;
            String picPath = qrPath + barCode + ".png";
            if (!new File(picPath).exists()) {//不存在就创建
                try {
                    QRCodeUtil.encode(barCode, null, picPath, barCode, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            sourceMaterial.barCode = picPath;
            printList.add(sourceMaterial);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", printList);
        String outFileName = UUID.randomUUID().toString() + ".pdf";
        pdfUtils.pdfTZ(map, outFileName);
        return String.format(pdfHost, outFileName);
    }

    /**
     * 保存数据（插入或更新）
     *
     * @param stInventoryBill
     */
    @Override
    @Transactional(readOnly = false)
    public void save(StInventoryBill stInventoryBill) {
        Integer billType = stInventoryBill.getInOrOut();
        //1要特殊处理
        if (stInventoryBill.getIsNewRecord()) {
            BillUtil.BillType[] values = BillUtil.BillType.values();
            for (BillUtil.BillType billTypeE : values) {
                if (billTypeE.getBillCode() == billType) {
                    //加个单号
                    String billNo = billUtil.billNo(billTypeE);//采购入库
                    stInventoryBill.setBillNo(billNo);
                    break;
                }
            }


        }
        super.save(stInventoryBill);
        // 保存 StInventoryBill子表
        for (StInventoryBillDetail stInventoryBillDetail : stInventoryBill.getStInventoryBillDetailList()) {
            if (!StInventoryBillDetail.STATUS_DELETE.equals(stInventoryBillDetail.getStatus())) {
                stInventoryBillDetail.setParentId(stInventoryBill);
                String billNo = stInventoryBill.getBillNo();
                if (stInventoryBillDetail.getIsNewRecord()) {
                    stInventoryBillDetail.setBillNo(billNo);
                    String code = null;
//                    if (billType == BillUtil.BillType.otherOutBill.getBillCode()) {
//                        StMaterialRecord stMaterialRecord = new StMaterialRecord();
//                        String materialName = stInventoryBillDetail.getMaterialName();
//
//                        stMaterialRecord.setMaterialCode(materialName);
//                        code = materialName;
//                        String id = stMaterialRecordService.findMP(stMaterialRecord).get(0).getId();
//                        stInventoryBillDetail.setMaterialName(id);
//                    } else {
                    StMaterialRecord stMaterialRecord = stMaterialRecordService.get(stInventoryBillDetail.getMaterialName());

                    if (stMaterialRecord == null) {
                        StProductRecord productRecord = stProductRecordService.get(stInventoryBillDetail.getMaterialName());
                        code = productRecord.getProductCode();
                    } else {
                        code = stMaterialRecord.getMaterialCode();
                    }

//                    if (BillUtil.BillType.purchaseInBill.getBillCode() != billType) {
//                        //和此处详情不是并生关系
//                        saveWarehouseInventory(billType, stInventoryBillDetail, billNo);
//                    }
                    stInventoryBillDetail.setBarCode(code + "_" + stInventoryBillDetail.getBatchNumber());
                    stInventoryBillDetailDao.insert(stInventoryBillDetail);
                } else {
                    stInventoryBillDetailDao.update(stInventoryBillDetail);
                    // fixme 应该是审核后一次性生成
//                    String id = stInventoryBillDetail.getId();
//                    StWarehouseInventory stNull = new StWarehouseInventory();
//                    stNull.setPrimaryDetailId(id);
//                    stNull.setBillNo(billNo);
//                    List<StWarehouseInventory> list = stWarehouseInventoryDao.findList(stNull);
//                    StWarehouseInventory warehouseInventory = list.get(0);//肯定能找到一个
//
//                    warehouseInventory.setBatchNumber(stInventoryBillDetail.getBatchNumber());
//                    Integer number = stInventoryBillDetail.getNumber();
//                    if (null == number) number = 0;
//                    warehouseInventory.setNumber(number.doubleValue());
//                    warehouseInventory.setMaterialName(stInventoryBillDetail.getMaterialName());
//                    warehouseInventory.setBillCategory(billType);//种类
//                    int inOrOut = BillJudge.judgeInOrOut(billType);
//                    if (BillJudge.allot != inOrOut) {//非调拨单直接操作
//                        warehouseInventory.setInOrOut(inOrOut);
//                        warehouseInventory.setWarehouse(stInventoryBillDetail.getWarehousePosition());
//                    } else {
//                        warehouseInventory.setNumber(stInventoryBillDetail.getAllotNumber().doubleValue());
//                        warehouseInventory.setInOrOut(0);//出库
//                        String allotOutWarehouse = stInventoryBillDetail.getAllotOutWarehouse();
//                        warehouseInventory.setWarehouse(allotOutWarehouse);
//                        StWarehouseInventory warehouseInventoryIn = list.get(1);
//                        String idTmp = warehouseInventoryIn.getId();
//                        BeanUtils.copyProperties(warehouseInventory, warehouseInventoryIn);
//                        warehouseInventoryIn.setId(idTmp);
//                        warehouseInventoryIn.setInOrOut(1);
//                        warehouseInventoryIn.setWarehouse(stInventoryBillDetail.getAllotInWarehouse());
//                        stWarehouseInventoryDao.update(warehouseInventoryIn);
//                    }
//                    if (BillUtil.BillType.purchaseInBill.getBillCode() != billType) {
//                        //采购单，审核之后直接插入
//                        stWarehouseInventoryDao.update(warehouseInventory);
//                    }
                }
                if (1 == billType) {

                    sendCheckLog(stInventoryBill, stInventoryBillDetail);
                }
            } else {

                stInventoryBillDetailDao.delete(stInventoryBillDetail);
            }
        }
    }

    private void saveWarehouseInventory(Integer billType, StInventoryBillDetail stInventoryBillDetail, String billNo) {
        String id = stInventoryBillDetail.getId();
        StWarehouseInventory warehouseInventory = new StWarehouseInventory();
        warehouseInventory.setBillNo(billNo);
        warehouseInventory.setBatchNumber(stInventoryBillDetail.getBatchNumber());
        warehouseInventory.setPrimaryDetailId(id);
        Integer number = stInventoryBillDetail.getNumber();
        if (null == number) number = 0;
        warehouseInventory.setNumber(new BigDecimal(number.doubleValue() + ""));
        String materialName = stInventoryBillDetail.getMaterialName();

        StMaterialRecord stMaterialRecord0 = new StMaterialRecord();
        stMaterialRecord0.setId(materialName);
        StMaterialRecord stMaterialRecord = stMaterialRecordService.findMP(stMaterialRecord0).get(0);
        warehouseInventory.setMaterialCode(stMaterialRecord.getMaterialCode());
        warehouseInventory.setProductDate(stInventoryBillDetail.getProductDate());
        warehouseInventory.setSavedType(stInventoryBillDetail.getSavedType());
        warehouseInventory.setPassDate(stInventoryBillDetail.getPassDate());

        warehouseInventory.setBillCategory(billType);//种类
        int inOrOut = BillJudge.judgeInOrOut(billType);

        if (BillJudge.allot != inOrOut) {//非调拨单直接操作
            warehouseInventory.setInOrOut(inOrOut);
            warehouseInventory.setWarehouse(stInventoryBillDetail.getWarehousePosition());
        } else {
            //调拨单
            warehouseInventory.setInOrOut(Constant.in_or_out.out);//出库
            String allotOutWarehouse = stInventoryBillDetail.getAllotOutWarehouse();
            warehouseInventory.setWarehouse(allotOutWarehouse);
            warehouseInventory.setNumber(new BigDecimal(stInventoryBillDetail.getAllotNumber() + ""));
            //
            StWarehouseInventory warehouseInventoryIn = new StWarehouseInventory();
            BeanUtils.copyProperties(warehouseInventory, warehouseInventoryIn);
            warehouseInventoryIn.setInOrOut(Constant.in_or_out.in);
            warehouseInventoryIn.setWarehouse(stInventoryBillDetail.getAllotInWarehouse());
            stWarehouseInventoryService.save(warehouseInventoryIn);
        }
        stWarehouseInventoryService.save(warehouseInventory);
    }

    // 新增和删除是成对的
    private void removeWarehouseLog(String id) {
        StWarehouseInventory stNull = new StWarehouseInventory();
        stNull.setPrimaryDetailId(id);
//            stNull.setBillNo(stInventoryBillDetail.getBillNo());
        List<StWarehouseInventory> list = stWarehouseInventoryService.findList(stNull);
        for (StWarehouseInventory warehouseInventory : list) {
            stWarehouseInventoryService.delete(warehouseInventory);
        }
    }

    /**
     * //采购单要抄送到送检
     *
     * @param stInventoryBill
     * @param stInventoryBillDetail
     */
    private void sendCheckLog(StInventoryBill stInventoryBill, StInventoryBillDetail stInventoryBillDetail) {
        //  单据号自己生成
        String billNo = billUtil.billNo(BillUtil.BillType.checkLogBill);
        StCheckLog stCheckLog = new StCheckLog();
        // -------------------------------------------------------------------------------------------------------------------------
        stCheckLog.setInventoryBillDetailId(stInventoryBillDetail.getId());
        // -------------------------------------------------------------------------------------------------------------------------


        String supplierId = stInventoryBill.getSupplierId();
        String materialName = stInventoryBillDetail.getMaterialName();
        String deptCode = stInventoryBill.getDeptCode();
        String deptName = stInventoryBill.getDeptName();
        String batchNumber = stInventoryBillDetail.getBatchNumber();
        Date productDate = stInventoryBillDetail.getProductDate();
        //保质期
        Integer savedType = stInventoryBillDetail.getSavedType();
        Date passDate = stInventoryBillDetail.getPassDate();
        //采购数量
        Integer number = stInventoryBillDetail.getNumber();

        List<StCheckLog> list = stCheckLogService.findList(stCheckLog);
        if (!list.isEmpty()) {
            stCheckLog = list.get(0);
        }

        // 允入数量
        Integer stockInNumber = 0;
        // 待检数量和采购一致
        stCheckLog.setSupplierId(supplierId);
        stCheckLog.setMaterialName(materialName);
        stCheckLog.setDeptCode(deptCode);
        stCheckLog.setBillNo(billNo);
        stCheckLog.setDeptName(deptName);
        stCheckLog.setBatchNumber(batchNumber);
        stCheckLog.setProductDate(productDate);
        stCheckLog.setSavedType(savedType);
        stCheckLog.setPassDate(passDate);
        stCheckLog.setBuyNumber(number);
        stCheckLog.setStockInNumber(stockInNumber);
        stCheckLog.setWaitCheckNumber(number.doubleValue());
        //todo 检验的明细还要生成
        stCheckLogService.save(stCheckLog);
    }

    /**
     * 更新状态
     *
     * @param stInventoryBill
     */
    @Override
    @Transactional(readOnly = false)
    public void updateStatus(StInventoryBill stInventoryBill) {
        super.updateStatus(stInventoryBill);
    }

    /**
     * 删除数据
     *
     * @param stInventoryBill
     */
    @Override
    @Transactional(readOnly = false)
    public void delete(StInventoryBill stInventoryBill) {
        super.delete(stInventoryBill);
        StInventoryBillDetail stInventoryBillDetail = new StInventoryBillDetail();
        stInventoryBillDetail.setParentId(stInventoryBill);
        List<StInventoryBillDetail> listChild = stInventoryBillDetailDao.findList(stInventoryBillDetail);

        for (StInventoryBillDetail inventoryBillDetail : listChild) {
            String id = inventoryBillDetail.getId();

            //删除检验单操作日志
            StCheckLog stCheckLog0 = new StCheckLog();
            stCheckLog0.setInventoryBillDetailId(id);
            List<StCheckLog> list1 = stCheckLogService.findList(stCheckLog0);
            for (StCheckLog stCheckLog : list1) {
                stCheckLogService.delete(stCheckLog);
            }

            //删除仓库操作日志
            removeWarehouseLog(id);
        }
        stInventoryBillDetailDao.deleteByEntity(stInventoryBillDetail);
    }


}